//
//  selectCollectModeView.m
//  dataGathering
//
//  Created by apple on 14-11-7.
//  Copyright (c) 2014年 shuili. All rights reserved.
//
#import <ImageIO/ImageIO.h>
#import "selectCollectModeView.h"
#import "MapMainView.h"

#define Size            150
#define FadeDuration    0.3
#define GifSpeed        0.3

#define APPDELEGATE     ((AppDelegate*)[[UIApplication sharedApplication] delegate])

#if __has_feature(objc_arc)
#define toCF (__bridge CFTypeRef)
#define fromCF (__bridge id)
#else
#define toCF (CFTypeRef)
#define fromCF (id)
#endif



#pragma mark - UIImage Animated GIF


@implementation UIImage (animatedGIF)

static int delayCentisecondsForImageAtIndex(CGImageSourceRef const source, size_t const i) {
    int delayCentiseconds = 1;
    CFDictionaryRef const properties = CGImageSourceCopyPropertiesAtIndex(source, i, NULL);
    if (properties) {
        CFDictionaryRef const gifProperties = CFDictionaryGetValue(properties, kCGImagePropertyGIFDictionary);
        if (gifProperties) {
            NSNumber *number = fromCF CFDictionaryGetValue(gifProperties, kCGImagePropertyGIFUnclampedDelayTime);
            if (number == NULL || [number doubleValue] == 0) {
                number = fromCF CFDictionaryGetValue(gifProperties, kCGImagePropertyGIFDelayTime);
            }
            if ([number doubleValue] > 0) {
                // Even though the GIF stores the delay as an integer number of centiseconds, ImageIO “helpfully” converts that to seconds for us.
                delayCentiseconds = (int)lrint([number doubleValue] * 100);
            }
        }
        CFRelease(properties);
    }
    return delayCentiseconds;
}

static void createImagesAndDelays(CGImageSourceRef source, size_t count, CGImageRef imagesOut[count], int delayCentisecondsOut[count]) {
    for (size_t i = 0; i < count; ++i) {
        imagesOut[i] = CGImageSourceCreateImageAtIndex(source, i, NULL);
        delayCentisecondsOut[i] = delayCentisecondsForImageAtIndex(source, i);
    }
}

static int sum(size_t const count, int const *const values) {
    int theSum = 0;
    for (size_t i = 0; i < count; ++i) {
        theSum += values[i];
    }
    return theSum;
}

static int pairGCD(int a, int b) {
    if (a < b)
        return pairGCD(b, a);
    while (true) {
        int const r = a % b;
        if (r == 0)
            return b;
        a = b;
        b = r;
    }
}

static int vectorGCD(size_t const count, int const *const values) {
    int gcd = values[0];
    for (size_t i = 1; i < count; ++i) {
        // Note that after I process the first few elements of the vector, `gcd` will probably be smaller than any remaining element.  By passing the smaller value as the second argument to `pairGCD`, I avoid making it swap the arguments.
        gcd = pairGCD(values[i], gcd);
    }
    return gcd;
}

static NSArray *frameArray(size_t const count, CGImageRef const images[count], int const delayCentiseconds[count], int const totalDurationCentiseconds) {
    int const gcd = vectorGCD(count, delayCentiseconds);
    size_t const frameCount = totalDurationCentiseconds / gcd;
    UIImage *frames[frameCount];
    for (size_t i = 0, f = 0; i < count; ++i) {
        UIImage *const frame = [UIImage imageWithCGImage:images[i]];
        for (size_t j = delayCentiseconds[i] / gcd; j > 0; --j) {
            frames[f++] = frame;
        }
    }
    return [NSArray arrayWithObjects:frames count:frameCount];
}

static void releaseImages(size_t const count, CGImageRef const images[count]) {
    for (size_t i = 0; i < count; ++i) {
        CGImageRelease(images[i]);
    }
}

static UIImage *animatedImageWithAnimatedGIFImageSource(CGImageSourceRef const source) {
    size_t const count = CGImageSourceGetCount(source);
    CGImageRef images[count];
    int delayCentiseconds[count]; // in centiseconds
    createImagesAndDelays(source, count, images, delayCentiseconds);
    int const totalDurationCentiseconds = sum(count, delayCentiseconds);
    NSArray *const frames = frameArray(count, images, delayCentiseconds, totalDurationCentiseconds);
    UIImage *const animation = [UIImage animatedImageWithImages:frames duration:(NSTimeInterval)totalDurationCentiseconds / 100.0];
    releaseImages(count, images);
    return animation;
}

static UIImage *animatedImageWithAnimatedGIFReleasingImageSource(CGImageSourceRef CF_RELEASES_ARGUMENT source) {
    if (source) {
        UIImage *const image = animatedImageWithAnimatedGIFImageSource(source);
        CFRelease(source);
        return image;
    } else {
        return nil;
    }
}

+ (UIImage *)animatedImageWithAnimatedGIFData:(NSData *)data {
    return animatedImageWithAnimatedGIFReleasingImageSource(CGImageSourceCreateWithData(toCF data, NULL));
}

+ (UIImage *)animatedImageWithAnimatedGIFURL:(NSURL *)url {
    return animatedImageWithAnimatedGIFReleasingImageSource(CGImageSourceCreateWithURL(toCF url, NULL));
}

@end


@interface selectCollectModeView ()
@property(nonatomic, retain)NSArray *collectTypeList;
@property(nonatomic, retain)NSArray *collectTypeNameList;
@property(nonatomic, retain)NSArray *collectTypeNameListPoint;
@property(nonatomic, retain)NSArray *collectTypeNameListPolyline;

@property(nonatomic, retain)UIButton *test;
@property(nonatomic, retain)UIImageView *image;
@property(nonatomic, retain)UILabel *recordLabel;
@property(nonatomic, retain)UIImageView *imageView;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UIButton *gpsDotButton;

@property (weak, nonatomic) IBOutlet UILabel *networkStrengthLabel;
@property (weak, nonatomic) IBOutlet UILabel *samplingFrequencyLabel;

@property (weak, nonatomic) IBOutlet UIImageView *gpsStrengthStatusImage;
@property (weak, nonatomic) IBOutlet UIImageView *networkStatusImage;
@property (weak, nonatomic) IBOutlet UILabel *gpsStatusImageLabel;
@property (weak, nonatomic) IBOutlet UILabel *networkStatusImageLabel;

@property (weak, nonatomic) IBOutlet UISlider *samplingRatioSlider;

@property (weak, nonatomic) NSTimer *gpsCheckingTimer;
@property (nonatomic, assign)NSInteger samplingRatio;


@end

@implementation selectCollectModeView




- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self initScrollView];
    
    _collectTypeList = [[NSArray alloc] initWithObjects:@"pic_绘制方式_u1021.png", @"pic_绘制方式_u1025.png",@"pic_绘制方式_u1029.png",@"pic_绘制方式_u1033.png",@"pic_绘制方式_u1037.png",@"pic_绘制方式_u1041.png", nil];
    _collectTypeNameList = [[NSArray alloc] initWithObjects:@"多边形", @"矩形",@"三角形",@"椭圆",@"正圆",@"手绘面", nil];
    
    _collectTypeNameListPoint = [[NSArray alloc] initWithObjects:@"点", nil];
    
    _collectTypeNameListPolyline = [[NSArray alloc] initWithObjects:@"直线", @"多段直线", @"手绘曲线", nil];
    
    [_backButton setImage:[UIImage imageNamed:@"u163_mouseOver.png"] forState:UIControlStateHighlighted];
    
    [_nameLabel setText:_titleName];
    
    [_handDrawButton setBackgroundImage:[UIImage imageNamed:@"u1014_selected.png"] forState:UIControlStateHighlighted];
    [_handDrawButton setBackgroundImage:[UIImage imageNamed:@"u1014_selected.png"] forState:UIControlStateSelected];
    [_handDrawButton setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    
    [_GPSButton setBackgroundImage:[UIImage imageNamed:@"u1014_selected.png"] forState:UIControlStateHighlighted];
    [_GPSButton setBackgroundImage:[UIImage imageNamed:@"u1014_selected.png"] forState:UIControlStateSelected];
    
    [_gpsDotButton setBackgroundImage:[UIImage imageNamed:@"u1014_selected.png"] forState:UIControlStateHighlighted];
    [_gpsDotButton setBackgroundImage:[UIImage imageNamed:@"u1014_selected.png"] forState:UIControlStateSelected];
    
    [_GPSButton setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    
    [_gpsDotButton setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    
    [self setHandDrawButtonSelected:YES];
    
    UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc] init];
    [layout setItemSize:CGSizeMake(144, 48)];
    [layout setMinimumInteritemSpacing:0];
    [layout setMinimumLineSpacing:0];
    
    
    UICollectionView *myCollectionView=[[UICollectionView alloc] initWithFrame:CGRectMake(0, 8, 288, 304) collectionViewLayout:layout];
    [myCollectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    myCollectionView.backgroundColor=[UIColor whiteColor];
    myCollectionView.delegate=self;
    myCollectionView.dataSource=self;
    [_scollView addSubview:myCollectionView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cancelRecording:) name:@"cancelRecordingLocation" object:nil];
    
    
    
}

-(void)cancelRecording:(NSNotification*)noti
{
    [_test setSelected:NO];
    [_recordLabel setText:@"开始采集GPS轨迹"];
}

- (void)initScrollView
{
    _scollView.pagingEnabled = YES;
    _scollView.clipsToBounds = NO;
    //_scollView.contentSize = CGSizeMake(_scollView.frame.size.width * 2, _scollView.frame.size.height);
    _scollView.scrollsToTop = NO;
    //_scollView.delegate = self;
    
    _test = [[UIButton alloc] initWithFrame:CGRectMake(_scollView.frame.size.width, 240, _scollView.frame.size.width-30, 48)];
    
    UIButton *dotRecordingButton = [[UIButton alloc] initWithFrame:CGRectMake(_scollView.frame.size.width, 210, _scollView.frame.size.width-30, 30)];
    
    UILabel *dotLabel = [[UILabel alloc] initWithFrame:CGRectMake(77, 3, 200, 24)];
    [dotLabel setText:@"打点采集"];
    [dotLabel setTextColor:[UIColor colorWithRed:151.0/256 green:151.0/256 blue:151.0/256 alpha:1]];
    [dotRecordingButton addSubview:dotLabel];

    
    
    //_image = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"pic_录制_u1045.png"]];
    //_image.frame = CGRectMake(41, 12, 24 , 24);
    //_image.contentMode = UIViewContentModeScaleAspectFit;
    //[_test addSubview:_image];
    
    _recordLabel = [[UILabel alloc] initWithFrame:CGRectMake(77, 12, 200, 24)];
    [_recordLabel setText:@"开始采集GPS轨迹"];
    [_recordLabel setTextColor:[UIColor colorWithRed:151.0/256 green:151.0/256 blue:151.0/256 alpha:1]];
    [_test addSubview:_recordLabel];
    
    
    [_scollView addSubview:_test];
    [_scollView addSubview:dotRecordingButton];
    
    [dotRecordingButton addTarget:self action:@selector(addDotLocation) forControlEvents:UIControlEventTouchUpInside];
    [_test addTarget:self action:@selector(testStartRecordingButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    
    
    _gpsCheckingTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(checkingGPSTimerMethod:) userInfo:nil repeats:YES];
    
    _samplingRatio = [(NSString*)[[NSUserDefaults standardUserDefaults] objectForKey:@"samplingFrequency"] integerValue];
    [_samplingRatioSlider setValue:_samplingRatio];
    NSString *samplingRatioString = [NSString stringWithFormat:@"%d次/分钟",(int)_samplingRatio];
    [_samplingFrequencyLabel setText:samplingRatioString];
}

-(void)addDotLocation
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"addDotLocation" object:nil];
}

-(void)checkingGPSTimerMethod:(NSTimer *)timer
{
    if([CLLocationManager locationServicesEnabled])
    {
        [_gpsStrengthStatusImage setImage:[UIImage imageNamed:@"u1236.png"]];
        [_gpsStatusImageLabel setText:@"优秀"];
    } else {
        [_gpsStrengthStatusImage setImage:[UIImage imageNamed:@"u1240.png"]];
        [_gpsStatusImageLabel setText:@"断开"];
    }
    
    if([[AFNetworkReachabilityManager sharedManager] isReachable]){
        [_networkStatusImage setImage:[UIImage imageNamed:@"u1236.png"]];
        [_networkStatusImageLabel setText:@"优秀"];
    } else {
        [_networkStatusImage setImage:[UIImage imageNamed:@"u1240.png"]];
        [_networkStatusImageLabel setText:@"断开"];
    }
    
}

- (void)testStartRecordingButtonClicked
{
    if(![_test isSelected]){
        [_test setSelected:YES];
        //[_test setBackgroundColor:[UIColor lightGrayColor]];
        [_image setImage:[UIImage imageNamed:@"pic_录制_u1045_selected.png"]];
        [_recordLabel setText:@"停止采集GPS轨迹"];
        
        for (UIView* next = [[self navigationController].parentViewController.view superview]; next; next = next.superview) {
            UIResponder* nextResponder = [next nextResponder];
            if ([nextResponder isKindOfClass:[UIViewController class]]) {
                [((MapMainView*)nextResponder) setGpsCollectingType:_collectedDataType];
            }
        }
        
        //_imageView = [[UIImageView alloc] initWithFrame:CGRectMake(_scollView.frame.size.width, 56, 288, 160)];
        //[_imageView setImage:[UIImage animatedImageWithAnimatedGIFURL:[[NSBundle mainBundle] URLForResource:@"pic_gps____u1047.gif" withExtension:nil]]];
        //[_scollView addSubview:_imageView];
        //[_imageView startAnimating];
        
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"startRecordingLocation" object:[NSNumber numberWithFloat:[_samplingRatioSlider value]]];
    } else {
        [_test setSelected:NO];
        //[_imageView stopAnimating];
        //[_imageView removeFromSuperview];
        //[_image setImage:[UIImage imageNamed:@"pic_录制_u1045.png"]];
        [_recordLabel setText:@"开始采集GPS轨迹"];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"pauseRecordingLocation" object:nil];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setHandDrawButtonSelected: (BOOL)selected
{
    [_handDrawButton setSelected:selected];
    [_GPSButton setSelected:!selected];
    [_gpsDotButton setSelected:!selected];
    
    [_scollView setContentOffset:CGPointMake(0, 0) animated:YES];
}

- (void)setGPSDrawButtonSelected: (BOOL)selected
{
    [_GPSButton setSelected:selected];
    [_handDrawButton setSelected:!selected];
    [_gpsDotButton setSelected:!selected];
    
    [_scollView setContentOffset:CGPointMake(_scollView.frame.size.width , 0) animated:YES];
}

- (void)setGPSDotDrawButtonSelected: (BOOL)selected
{
    [_gpsDotButton setSelected:selected];
    [_GPSButton setSelected:!selected];
    [_handDrawButton setSelected:!selected];
    
    [_scollView setContentOffset:CGPointMake(_scollView.frame.size.width*2 , 0) animated:YES];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)backButtonClicked:(id)sender {
    [((UINavigationController*)(self.parentViewController)) popViewControllerAnimated:YES];
}

- (IBAction)cancelButtonClicked:(id)sender {
    for (UIView* next = [[self navigationController].parentViewController.view superview]; next; next = next.superview) {
        UIResponder* nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            [((MapMainView*)nextResponder) removeNewDataWindow];
        }
    }
}
- (IBAction)handDrawButtonClicked:(id)sender {
    [self setHandDrawButtonSelected:YES];
}

- (IBAction)GPSButtonClicked:(id)sender {
    [self setGPSDrawButtonSelected:YES];
}

- (IBAction)GPSDotButtonClicked:(id)sender {
    [self setGPSDotDrawButtonSelected:YES];
}

#pragma UICollectionViewDatasource methods
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if([_collectedDataType isEqualToString:@"POLYGON"] || [_collectedDataType isEqualToString:@"polygon"])
    {
        return 6;
    } else if ([[_collectedDataType uppercaseString] isEqualToString:@"POLYLINE"] || [[_collectedDataType uppercaseString] isEqualToString:@"Polyline"])
    {
        return 2;
    } else {
        return 1;
    }
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    return 1;
}

//Cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UIColor *nameTextColor = [UIColor colorWithRed:151.0/256.0 green:151.0/256.0 blue:151.0/256.0 alpha:1];
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    cell.contentView.frame = CGRectMake(0, 0, 144, 48);

    
    UIImageView *view = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[_collectTypeList objectAtIndex:[indexPath row]]]];
    view.frame = CGRectMake(8, 12, 24 , 24);
    view.contentMode = UIViewContentModeScaleAspectFit;
    [cell.contentView addSubview:view];
    
    UILabel *namelabel = [[UILabel alloc] initWithFrame:CGRectMake(51, 15, 42 , 17)];
    if([[_collectedDataType uppercaseString] isEqualToString:@"POLYGON"] || [_collectedDataType isEqualToString:@"polygon"])
    {
        [namelabel setText:[_collectTypeNameList objectAtIndex:[indexPath row]]];
    } else if ([[_collectedDataType uppercaseString] isEqualToString:@"POLYLINE"] || [_collectedDataType isEqualToString:@"Polyline"])
    {
        [namelabel setText:[_collectTypeNameListPolyline objectAtIndex:[indexPath row]]];
    } else {
        [namelabel setText:[_collectTypeNameListPoint objectAtIndex:[indexPath row]]];
    }
    //[namelabel setText:[_collectTypeNameList objectAtIndex:[indexPath row]]];
    [namelabel setTextColor:nameTextColor];
    [namelabel setFont:[UIFont systemFontOfSize:14]];
    [cell.contentView addSubview:namelabel];
    
    UIImageView *selectedBackView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"u1019_selected.png"]];
    selectedBackView.frame = cell.contentView.frame;
    selectedBackView.contentMode = UIViewContentModeScaleAspectFit;
    cell.selectedBackgroundView = selectedBackView;
    [cell sizeToFit];
    
    return cell;
}

#pragma UICollectionView Delegate methods
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    for (UIView* next = [[self navigationController].parentViewController.view superview]; next; next = next.superview) {
        UIResponder* nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            if([[_collectedDataType uppercaseString] isEqualToString:@"POLYLINE"])
            {
                [((MapMainView*)nextResponder) beginHandDrawingMode:([indexPath item]+6) :_collectedDataType];

            } else if([[_collectedDataType uppercaseString] isEqualToString:@"POLYGON"]){
                [((MapMainView*)nextResponder) beginHandDrawingMode:([indexPath item]) :_collectedDataType];
            } else {
                [((MapMainView*)nextResponder) beginHandDrawingMode:([indexPath item]+9) :_collectedDataType];
            }
        }
    }
    [[collectionView cellForItemAtIndexPath:indexPath] setSelected:NO];
    [self cancelButtonClicked :nil];

}

- (void)viewWillAppear:(BOOL)animated
{
    if(!_scollView){
        return;
    }
    if([_handDrawButton isSelected]){
        [_scollView setContentOffset:CGPointMake(0, 0) animated:YES];
    } else {
        [_scollView setContentOffset:CGPointMake(_scollView.frame.size.width , 0) animated:YES];
    }
    [super viewWillAppear:animated];
    
}


- (IBAction)sliderValueChanged:(id)sender {
    _samplingRatio = [_samplingRatioSlider value];
    NSString *samplingRatioString = [NSString stringWithFormat:@"%d次/分钟",(int)_samplingRatio];
    [_samplingFrequencyLabel setText:samplingRatioString];
    
    NSString *samplingRatio = [NSString stringWithFormat:@"%d",(int)[_samplingRatioSlider value]];
    [[NSUserDefaults standardUserDefaults] setObject:samplingRatio forKey:@"samplingFrequency"];
}



/*
-(void)collectionView:(UICollectionView *)collectionView didHighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
    cell.backgroundColor = [UIColor blueColor];
}

-(void)collectionView:(UICollectionView *)collectionView didUnhighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
}
 */

@end
